import { Injectable } from '@nestjs/common';
import { Guard } from '../../guard/constants/guard.constant';
import { Role } from '../../role/constants/role.constant';
import { UserEntity } from '../entities/user.entity';
import { UserService } from '../services/user.service';

@Injectable()
export class UserUtil {
  constructor(private readonly userService: UserService) {}

  /**
   * 获取角色和权限列表
   * @param user 用户实体
   */
  async getRoleAndGuardList(user: UserEntity): Promise<{ roleList: Role[]; guardList: Guard[] }> {
    if (!user || !user.roleList) return null;

    const roleNameList = [];
    const guardNameList = [];
    for (const role of user.roleList) {
      if (!roleNameList.includes(role.name)) roleNameList.push(role.name);

      for (const guard of role.guardList) {
        if (!guardNameList.includes(guard.name)) guardNameList.push(guard.name);
      }
    }

    const roleList = [...new Set(roleNameList)];
    console.log(JSON.stringify(roleNameList));

    const guardList = [...new Set(guardNameList)];
    console.log(JSON.stringify(guardList));

    return { roleList, guardList };
  }

  /**
   * 获取用户权限列表
   * @param user 用户实体
   */
  async getGuardList(user: UserEntity): Promise<Guard[]> {
    if (!user || !user.roleList) return null;

    const guardNameList = [];
    for (const role of user.roleList) {
      for (const guard of role.guardList) {
        if (!guardNameList.includes(guard.name)) guardNameList.push(guard.name);
      }
    }

    const guardList = [...new Set(guardNameList)];
    console.log(JSON.stringify(guardList));

    return guardList;
  }

  /**
   * 获取用户权限列表
   * @param userUuid 用户Uuid
   */
  async getGuardListByUserUuid(userUuid: string): Promise<{ user: UserEntity; guardList: Guard[] }> {
    if (!userUuid) return null;

    const user = await this.userService.findOneByUuid(userUuid);
    if (!user || !user.roleList) return null;

    const guardNameList = [];
    for (const role of user.roleList) {
      for (const guard of role.guardList) {
        if (!guardNameList.includes(guard.name)) guardNameList.push(guard.name);
      }
    }

    const guardList = [...new Set(guardNameList)];
    console.log(JSON.stringify(guardList));

    return { user, guardList };
  }
}
